<template>
	<jk-dialog
		v-model="showDialog"
		:title="`${pageType === 'edit' ? '编辑' : pageType === 'add' ? '新增' : '详情'}-机物料出库申请`"
		width="1160px"
		:show-content-loading="showLoading"
		:confirm-btn-loading="saveBtnLoading"
		:show-confirm-btn="pageType !== 'detail'"
		:show-cancel-btn="pageType !== 'detail'"
		:show-close-btn="pageType === 'detail'"
		@on-close="onVisibleChange(false)"
		@on-cancel="onVisibleChange(false)"
		@on-visible-change="onVisibleChange"
		@on-confirm="onConfirmBtn"
	>
		<el-form ref="ruleForm" :model="ruleForm" :rules="rules" :hide-required-asterisk="pageType === 'detail' || ruleForm.auditState === 1" label-width="110px" :show-message="false">
			<div ref="box1">
				<div class="flex-start-center margin-bottom-4" style="font-size: 13px;">
					<el-tag v-if="!ruleForm.code" type="primary" effect="plain" class="">
						<span class="el-icon-tickets item-gap"></span>
						<span>基本信息</span>
					</el-tag>
					<div v-else style="font-size: 16px;">
						<span class="el-icon-star-off item-gap"></span>
						<span>{{ ruleForm.code || '系统自动生成' }}</span>
					</div>
				</div>
				<jk-card>
					<el-row class="flex-start-center-wrap">
						<el-col :span="8">
							<el-form-item class="margin-bottom-10" label="区域" prop="workshopId">
								<span v-if="pageType === 'detail' || ruleForm.auditState === 1 || pageType === 'edit'" class="read-only-2">{{ ruleForm.workshopName }}</span>
								<jk-select v-else v-model="ruleForm.workshopId" class="width-100-percent" size="medium" :option-list="workshopList" placeholder="" />
							</el-form-item>
						</el-col>
						<el-col :span="8">
							<el-form-item class="margin-bottom-10" label="日期" prop="minValue">
								<span v-if="pageType === 'detail' || ruleForm.auditState === 1 || pageType === 'edit'" class="read-only-2">{{ ruleForm.belongDate }}</span>
								<jk-date-picker v-else v-model="ruleForm.belongDate" size="medium" placeholder="" />
							</el-form-item>
						</el-col>
						<el-col :span="8">
							<el-form-item class="margin-bottom-10" label="仓库" prop="warehouseId">
								<span v-if="pageType === 'detail' || ruleForm.auditState === 1" class="read-only-2">{{ ruleForm.warehouseName }}</span>
								<jk-select v-else v-model="ruleForm.warehouseId" :option-list="warehouseList" class="width-100-percent" size="medium" placeholder="仓库" @change="onWarehouseChange" />
							</el-form-item>
						</el-col>
						<el-col :span="8">
							<el-form-item class="margin-bottom-10" label="出库类别" prop="typeId">
								<span v-if="pageType === 'detail' || ruleForm.auditState === 1" class="read-only-2">{{ ruleForm.typeName }}</span>
								<jk-select v-else v-model="ruleForm.typeId" :option-list="typeList" class="width-100-percent" size="medium" placeholder="" />
							</el-form-item>
						</el-col>
						<el-col :span="8">
							<el-form-item class="margin-bottom-10" label="部门" prop="deptId">
								<span v-if="pageType === 'detail' || ruleForm.auditState === 1" class="read-only-2">{{ ruleForm.deptName }}</span>
								<jk-cascader v-else v-model="ruleForm.deptId" :option-list="deptList" class="width-100-percent" size="medium" placeholder="部门" @change="onDeptChange" />
							</el-form-item>
						</el-col>
						<el-col :span="24">
							<el-form-item class="margin-bottom-0" label="备注">
								<span v-if="pageType === 'detail' || ruleForm.auditState === 1" class="read-only-2">{{ ruleForm.remark }}</span>
								<el-input v-else v-model="ruleForm.remark" :rows="1" type="textarea" placeholder="" />
							</el-form-item>
						</el-col>
					</el-row>
				</jk-card>
				<el-tag class="margin-bottom-4 el-icon-tickets margin-top-10" effect="plain">物料明细</el-tag>
			</div>
			<jk-table border :data="ruleForm.itemList" :height="dialogTableHeight - 20">
				<vxe-column title="操作" align="center" field="operation" :width="70">
					<template slot-scope="scope">
						<div class="flex-center">
							<jk-button size="mini" :disabled="pageType === 'detail'" icon="el-icon-minus" @click="ruleForm.itemList.splice(scope.rowIndex, 1)" />
						</div>
					</template>
				</vxe-column>
				<vxe-column title="物料" align="left" field="productName" :min-width="100"></vxe-column>
				<vxe-column title="批号" align="left" field="batchCode" prop="batchNumber" :min-width="220">
					<template slot-scope="scope">
						<remote-search-batch-code-input
							size="mini"
							:disabled="pageType === 'detail'"
							placeholder="批号"
							only-key="batchId"
							query-name="batchCode"
							:form-data="scope.row"
							@on-select="onSelectProductChange($event, scope.rowIndex)"
						></remote-search-batch-code-input>
					</template>
				</vxe-column>
				<vxe-column title="单位" align="left" field="unitName" :width="70"></vxe-column>
				<vxe-column title="件数" align="right" field="qty" :width="60"></vxe-column>
				<vxe-column title="单价" align="right" field="unitPrice" :min-width="70"></vxe-column>
				<vxe-column title="金额" align="right" field="money" :width="70"></vxe-column>
				<vxe-column title="项目" align="right" field="itemName" :width="70"></vxe-column>
				<vxe-column title="申请数" align="right" field="applyQty" :width="100">
					<template slot-scope="scope">
						<span v-if="pageType === 'detail' || ruleForm.auditState === 1">{{ scope.row.applyQty }}</span>
						<jk-number-input v-else v-model="scope.row.applyQty" size="mini" placeholder="" />
					</template>
				</vxe-column>
				<vxe-column title="已入库 货位" align="right" field="itemName" :width="200">
					<template slot="header">
						<el-row :gutter="6">
							<el-col :span="8" class="flex-end-center">已入库</el-col>
							<el-col :span="5">货位</el-col>
						</el-row>
					</template>
					<template slot-scope="scope">
						<el-row
							v-for="(saleOrderItem, saleOrderIndex) in scope.row.saleOrderList || [{}]"
							:key="saleOrderIndex"
							:gutter="24"
							class="flex-start-center"
						>
							<el-col class="flex-end-center" :span="8">
								<span>{{ saleOrderItem.inPackageQty || '0' }}</span>
							</el-col>
							<el-col :span="16">
								<jk-select v-model="scope.row.positionId" :disabled="pageType === 'detail'" :option-list="positionList" placeholder="货位" size="mini" class="width-100-percent"></jk-select>
							</el-col>
						</el-row>
					</template>
				</vxe-column>
				<vxe-column title="本次入库" align="right" field="thisTimeNum" :width="70">
					<template slot-scope="scope">
						<el-input v-model="scope.row.thisTimeNum" :rows="1" type="textarea" :disabled="pageType === 'detail'" :option-list="typeList" class="width-100-percent" size="mini" placeholder="" />
					</template>
				</vxe-column>
			</jk-table>
		</el-form>
	</jk-dialog>
</template>

<script>
    import calHeight from '/src/mixins/cal-dialog-height';
    import { getExamineParticularsGet, updateSuppliesDeliveryListPost } from '/src/api/machine/machineSuppliesDeliveryList.js';
    import remoteSearchProductInput from '../../technology/order/components/remote-search-product-input';
    import remoteSearchBatchCodeInput from '../../../views/production/qhPrd/productConfigCotton/components/remote-search-batch-code-input/index.vue';
    import { formatDate } from '../../../utils/jk/jk-tool';
    import { listDept } from '../../../api/system/dept';
    import jkCascader from '../machineMaterialOutWarehouseApplication/components/jk-cascader.vue';
    // 获取仓库接口
    import {
        spinWarehousePage, spinPositionPage
    } from '../../../api/production/package';
    export default {
        mixins: [calHeight],
        components: { remoteSearchProductInput, remoteSearchBatchCodeInput, jkCascader },
        props: {
            pageType: {
                type: String,
                default: ''
            },
            dialogState: {
                type: Boolean,
                default: false
            },
            dataId: {
                type: [String, Number],
                default: ''
            }
        },
        data() {
            return {
                tableLoading: false,
                saveBtnLoading: false,
                workshopList: [],
                showDialog: false,
                showLoading: true,
                confirmBtnLoading: false,
                saveDialogState: false,
                positionList: [],
                ruleForm: {
                    'minValue': null,
                    'maxValue': null,
                    'auditState': 0,
                    'remark': '',
                    'warehouseId': '',
                    'itemList': [{

                        saleOrderList: [
                        ]
                    }]
                },
                rules: {
                    warehouseId: [{ required: true, trigger: 'change' }],
                    maxValue: [{ required: true, trigger: 'change' }],
                    typeId: [{ required: true, trigger: 'change' }],
                    deptId: [{ required: true, trigger: 'change' }]
                },
                typeList: [
                    { id: 1, code: 'A', name: '自制成品入库' },
                    { id: 2, code: 'B', name: '下脚料入库' }
                ],
                defaultRowData: {
                    'processId': '',
                    'processCode': '',
                    'processName': '',
                    'unitPrice': 0
                },
                warehouseList: [], // 仓库数据
                deptList: [] // 部门数据
            };
        },
        methods: {
            getPositionListRequest() {
                if (!this.ruleForm.warehouseId) return;
                spinPositionPage({
                    warehouseId: this.ruleForm.warehouseId
                }).then(res => {
                    if (res.data.status === 200) {
                        this.positionList = res.data.res || [];
                    }
                });
            },
            // 选择下拉框数据清空
            onWarehouseChange(e) {
                this.ruleForm.itemList.forEach(x => {
                    this.$set(x, 'positionId', null);
                    this.$set(x, 'positionCode', '');
                    this.$set(x, 'positionName', '');
                    this.$set(x, 'thisTimeNum', '');
                });
                this.getPositionListRequest();
            },
            // 获取部门
            getTreeListRequest() {
                return listDept({ auditState: 1 }).then(res => {
                    if (res.data.status === 200) {
                        this.deptList = res.data.res || {};
                    }
                });
            },
            // 选择部门
            onDeptChange(id, e) {
                this.$set(this.ruleForm, 'deptId', e.id);
                this.$set(this.ruleForm, 'deptCode', e.code);
                this.$set(this.ruleForm, 'deptName', e.name);
            },
            onDeleteBtn(scope) {
                this.ruleForm.itemList.splice(scope.rowIndex, 1);
            },
            onAddBtn() {
                this.ruleForm.itemList.push(JSON.parse(JSON.stringify(this.defaultRowData)));
            },
            getParamData() {
                const params = JSON.parse(JSON.stringify(this.ruleForm));
                const workshopItem = this.workshopList.find(x => x.id === params.workshopId) || {};
                params.workshopCode = workshopItem.code;
                params.workshopName = workshopItem.name;

                const warehouseItem = this.warehouseList.find(x => x.id === params.warehouseId) || {};
                params.warehouseCode = warehouseItem.code;
                params.warehouseName = warehouseItem.name;

                const typeItem = this.typeList.find(x => x.id === params.typeId) || {};
                params.typeCode = typeItem.code;
                params.typeName = typeItem.name;
                let positionItem = {};
                params.itemList.forEach(orderItem => {
                    positionItem = this.positionList.find(x => x.id === orderItem.positionId) || {};
                    orderItem.positionCode = positionItem.code;
                    orderItem.positionName = positionItem.name;
                });

                if (!this.dataId) {
                    params.auditState = 1;
                    delete params.id;
                }
                return params;
            },
            onConfirmBtn() {
                this.$refs['ruleForm'].validate(valid => {
                    if (valid) {
                        this.createAndUpdateRequest();
                    } else {
                        this.$tipsBar(this, 'validator');
                    }
                });
            },
            createAndUpdateRequest() {
                const api = updateSuppliesDeliveryListPost;
                this.saveBtnLoading = true;
                api(this.getParamData()).then(res => {
                    this.saveBtnLoading = false;
                    if (res.data.status === 200) {
                        this.$tipsBar(this, 'save');
                        this.$emit('on-finish', res.data.res);
                    }
                });
            },
            onVisibleChange(e) {
                this.$emit('on-visible-change', e);
                if (!e) {
                    Object.assign(this.$data, this.$options.data());
                    this.$nextTick(() => {
                        this.$refs.ruleForm.resetFields();
                    });
                }
            },
            getDetailRequest() {
                return getExamineParticularsGet({ id: this.dataId }).then(res => {
                    if (res.data.status === 200) {
                        const resData = res.data.res || {};
                        this.ruleForm.itemList = resData.itemList || [];
                        this.ruleForm = res.data.res;
                    }
                });
            },
            getWarehouseListRequest() {
                return spinWarehousePage().then(res => {
                    if (res.data.status === 200) {
                        this.warehouseList = res.data.res || {};
                    }
                });
            },
            async getDependentData() {
                this.showLoading = true;
                this.workshopList = this.$store.state.user.userWorkshop.workshopList || [];
                if (!this.dataId) {
                    this.$set(this.ruleForm, 'workshopId', this.$route.query.workshopId ? Number(this.$route.query.workshopId) : this.$store.state.user.userWorkshop.defaultWorkshopId);
                    this.$set(this.ruleForm, 'belongDate', formatDate(Date.now()));
                }
                if (this.dataId) await this.getDetailRequest();
                await this.getTreeListRequest();
                await this.getWarehouseListRequest();
                await this.getPositionListRequest();
                this.showLoading = false;
            }
        },
        watch: {
            dialogState(newVal) {
                this.showDialog = newVal;
                if (newVal) {
                    this.getDependentData();
                }
            }
        }
    };
</script>
